package servlets;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Prevoznik;
import model.User;
import model.Util;
import app.PMF;

@SuppressWarnings("serial")
public class LogInServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {

		resp.setContentType("text/html; charset=utf-8");

		System.out.println("\n\tStartovan logInServlet");
		PersistenceManager pm = PMF.get().getPersistenceManager();

		// stavljamo test podatke
		//Util.napuniTestPodatke(pm);		

		System.out.println("logInServlet: Inicijalizovan");
		/*
		Extent<PutnaDuz> ex = pm.getExtent(PutnaDuz.class, true);
		Iterator<PutnaDuz> i = ex.iterator();
		while (i.hasNext()) {
			PutnaDuz pd = i.next();
			System.out.println("## putnaduz:"+pd);
		}*/

		HttpSession session = req.getSession(true);
		String uname = req.getParameter("username");
		String passwd = req.getParameter("password");
		String logoff = req.getParameter("logOff");
		User user = (User) session.getAttribute("user");

		try {
			// ako imamo user objekat u sesiji
			if (user != null) {
				// ako trebamo izlogovati korisnika
				if (logoff != null && logoff.equals("true")) {
					// ako je poslat parametar za logoff, odjavljujemo se

					user.setLoggedIn(false);
					pm.makePersistent(user);

					user.setUsername(null);
					user.setPassword(null);
					user.setLoggedIn(false);

					// pravimo novu sesiju
					req.getSession().invalidate();
					session = req.getSession();
					session.setAttribute("user", user);

					System.out.println("\n\t Izlogovali smo se uspesno");

					// i odemo na pocetnu stranicu
					RequestDispatcher disp = req
					.getRequestDispatcher("WebContent/logIn.jsp");
					// redirektovacemo na login stranicu
					disp.forward(req, resp);
					return;
				}

				User tmpUser = new User(uname, passwd);
				User readedUser = Util.getUser(uname, passwd);

				// ako trebamo logovati korisnika
				if (readedUser != null && uname != null && passwd != null
						&& tmpUser.equals(readedUser)) {
					// && !readedUser.isLoggedIn()){
					user = readedUser;
					user.setLoggedIn(true);
					pm.makePersistent(user);
					session.setAttribute("user", user);
					System.out.println("\n\tLOGUJEMO: " + user);

					// && !readedUser.isLoggedIn()){
					System.out.println("\n\tUspelo logovanje!!!");
					// ako je uspelo logovanje setujemo bean user
					
					System.out.println("Prosledjujemo na servlet za red voznje...");

					RequestDispatcher disp;
					if (user.isAdmin()) {
						disp = req.getRequestDispatcher("/admin");
					} else {
						// dodajemo i prevoznika u sesiju
						Prevoznik prevoznik = Util.getPrevoznikByUser(user);
						session.setAttribute("prevoznik", prevoznik);
						disp = req.getRequestDispatcher("/timeTableServlet");
					}
					System.out.println("\n\tRedirektujemo na red voznje...");
					disp.forward(req, resp);
					return;

				} else {
					// ako nisu lepo uneti username i password vracamo se na
					// login stranicu i ispisujemo poruku
					session.setAttribute("msg", "Uneti neisptavni podaci!");

					RequestDispatcher disp = req
					.getRequestDispatcher("/WebContent/logIn.jsp");
					disp.forward(req, resp);
				}
			} else {
				System.out.println("logInServlet: user == null");
				// ako user ne postoji, neko je pokusao direktno da gadja ovaj
				// servlet
				RequestDispatcher disp = req
				.getRequestDispatcher("/WebContent/logIn.jsp");
				disp.forward(req, resp);
			}
		} catch (Exception e) {

		} finally {
			pm.close();
		}
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		try {

			String logOff = req.getParameter("logOff");

			if (logOff != null && logOff.equals("true")) {
				HttpSession session = req.getSession(true);
				session.invalidate();

				RequestDispatcher disp = req
				.getRequestDispatcher("WebContent/logIn.jsp");
				disp.forward(req, resp);
			}
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
